package com.zisu.cx.graphsExpress;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @Author: 蔡翔
 * @Date: 2020/1/4 18:53
 * @Version 1.0
 *
 * 邻接矩阵
 */

public class AdjMatrix {
    private int V;
    private int E;
    private int[][] adj;

    //从文件中读取 图的相关信息
    public AdjMatrix(String fileName){
        File file = new File(fileName);
        // 写在try()里面申请资源，当调用结束后会自动回收。
        try(Scanner scanner = new Scanner(file)) {
            //第一个读到的代表定点  7 个定点 9 条边
            V = scanner.nextInt();
            if(V < 0){
                throw new IllegalArgumentException("V = 0");
            }
            adj = new int[V][V];

            E = scanner.nextInt();
            if(E <0){
                throw new IllegalArgumentException("边数必须大于0");
            }
            for(int i=0;i<E;i++){
                int a = scanner.nextInt();
                validateVertex(a);
                int b = scanner.nextInt();
                validateVertex(b);
                if(a == b){
                    throw new IllegalArgumentException("不允许存在自环边");
                }
                if(adj[a][b] == 1 ){
                    throw new IllegalArgumentException("不允许存在平行边");
                }
                adj[a][b] = 1;
                adj[b][a] = 1;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //V(节点合法性判断)
    private void validateVertex(int v){
        if(v<0 || v>V){
            throw new IllegalArgumentException("v值 : "+v+" 异常");
        }
    }

    //目的是不让用户可以修改V、E，，只能查看
    public int V(){
        return V;
    }

    public int E(){
        return E;
    }

    public boolean hasEdge(int v,int w){
        validateVertex(v);
        validateVertex(w);
        return adj[v][w] == 1;
    }

    //和v 相邻的节点
    public ArrayList<Integer> adj(int v){
        validateVertex(v);
        ArrayList<Integer> res = new ArrayList<>();
        for(int i =0;i<V;i++){
            if(adj[v][i] == 1){
                res.add(i);
            }
        }
        return res;
    }

    //度 就是这个节点有几个相邻的节点
    public int degree(int v){
        return adj(v).size();
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append(String.format("V = %d , E = %d \n" , V , E));
        for(int i =0;i<V ;i++){
            for(int j = 0;j<V;j++){
                str.append(String.format(" %d",adj[i][j]));
            }
            str.append('\n');
        }

        return str.toString();
    }

    public static void main(String[] args) {
        AdjMatrix adjMatrix = new AdjMatrix("g.txt");
        System.out.println(adjMatrix);
    }
}
